<template>
<div class="mian" :style="{'overflow': isShowShared ? 'hidden' : ''}">
    <div class="app-pagemian relative" ref="appPageRef">
        <!-- 用户初始看到的内容 -->
        <transition name="el-fade-in-linear">
            <div v-if="!resultImgUrl" onselectstart="return false">
                <img src="@/assets/event_images/event_face/img-event-face-nan.png" width="134" class="absolute z_index_9 my_img_1" @click="changeSex(0)">

                <img src="@/assets/event_images/event_face/img-event-face-nv.png" width="134" class="absolute z_index_9 my_img_2" @click="changeSex(1)">

                <img src="@/assets/event_images/event_face/img-event-face-kuang.png" width="147.5" class="absolute z_index_9 my_img_3" :class="userSex == 0 ? 'left' : 'right'">

                <img src="@/assets/event_images/event_face/img-event-face-mode1.png" height="280" class="absolute z_index_9 my_img_6" v-show="userSex == 0">

                <img src="@/assets/event_images/event_face/img-event-face-mode2.png" height="280" class="absolute z_index_9 my_img_6" v-show="userSex == 1">

                <img src="@/assets/event_images/event_face/img-event-face-start.png" width="298.5" height="51" class="absolute z_index_9 my_img_4" @click="openLoginPage()">

                <!-- 测试 -->
                <input type="file" class="my_file_input absolute z_index_9 " ref="fileRef" :accept="'image/*'" :multiple="false" @change="uploadImgFile($event)" v-if="userID">

                <img :src="baseImgUrl + '/middleground/storeclass/20210118/aefdc663be4949e684681b1470620925_.png'" width="347" class="absolute z_index_9 my_img_5">

                <div class="event_rule">
                    <p>活动规则：</p>
                    <p>1.选择您的性别，上传您的正面照片，即可制作您的专属形象拜年照。</p>
                    <p>2.为使照片更完美，请注意上传照片不要有遮挡哦~</p>
                    <p>本活动最终解释权归青岛云裳羽衣物联科技有限公司所有。</p>
                </div>
            </div>
        </transition>

        <!-- 用户上传完成自拍照后显示的页面内容 -->
        <transition name="el-fade-in-linear">
            <div v-if="resultImgUrl" onselectstart="return false">
                <img :src="resultImgUrl" height="375" class="absolute z_index_9 my_img_7">
                <div class="absolute z_index_9 my_btn_box">
                    <div class="custom_btn my_btn_1 text-center" @click="openYearPage()">
                        <img :src="baseImgUrl + '/middleground/storeclass/20210120/b388847dffe54348abee054b642c4d93_.png'" width="20" height="20">
                        <span class="font-size--xs">&emsp;购买您的拜年新衣</span>
                    </div>

                    <div class="custom_btn my_btn_2 text-center" @click="resetOption()">
                        <span class="font-size--xs">再玩一次</span>
                    </div>

                    <div class="flex align-center space-between">
                        <div class="my_btn_3 text-center" @click="renderSharedImg()">
                            <span class="font-size--xs">保存到相册</span>
                        </div>

                        <div class="my_btn_4 text-center" @click="postMiniProgramMsg()">
                            <span class="font-size--xs">分享给好友</span>
                        </div>
                    </div>
                </div>
            </div>
        </transition>
    </div>

    <!-- 购物车 -->
    <div class="buy_car_box flex align-center space-between" onselectstart="return false" v-if="!resultImgUrl">
        <div class="flex align-center flex-start" @click="openYearPage()">
            <img src="@/assets/event_images/event_face/img-event-face-logo.png" width="45">
            <div class="buy_car_title">
                <h5>购买您的拜年新衣</h5>
                <p>年货大集，一站备齐</p>
            </div>
        </div>
        <div class="buy_car_btn" @click="openYearPage()">一键购年货</div>
    </div>

    <!-- 生成图片的div -->
    <div class="shared_box absolute" ref="sharedRef">
        <img :src="resultImg64" width="752" class="my_img_8" v-if="resultImg64">

        <img src="@/assets/event_images/event_face/bg-event-face-logo.png" width="752" class="absolute my_img_9" v-if="userChannel == 1">
        <img src="@/assets/event_images/event_face/bg-event-face-logo2.png" width="752" class="absolute my_img_9" v-else-if="userChannel == 2">
    </div>

    <transition name="el-zoom-in-top">
        <div class="absolute modal padding_15" v-if="isShowShared">
            <img :src="html2canvasImg" height="80%">
            <p>长按图片进行保存</p>
            <p><i class="el-icon-circle-close font-size--lg" @click="isShowShared = false"></i></p>
        </div>
    </transition>

    <transition name="el-zoom-in-top">
        <div class="absolute modal padding_15" v-if="isShowShared2" @click="isShowShared2 = false">
            <p class="text-right" style="padding-right: 44px"><i class="el-icon-s-promotion" style="font-size:42px"></i></p>
            <br>
            <p>好了，现在招呼你的朋友们</p>
            <p>一起来玩吧</p>
        </div>
    </transition>

    <div class="el-loading-mask is-fullscreen" style="background: transparent;z-index: 2001;" v-if="loading">
        <div class="el-loading-spinner">
            <img src="@/assets/event_images/event_face/loading.gif" width="45">
            <p class="el-loading-text">拼命加载中...</p>
        </div>
    </div>
</div>
</template>

<script>
import exif from 'exif-js';
import html2canvas from 'html2canvas';
import { MergeYearFace, GetMergeYearFaceResult } from '@/views/event-management/services/index';
export default {
    data() {
        return {
            isIOS: false,
            isIOSVersion: [],
            loading: false,
            userSex: 0, // 1女 0男
            userID: '',
            userChannel: 1, // 用户渠道1云镜2洗衣先生4微服务5三翼鸟
            imageTypeList: ['image/jpeg', 'image/png', 'image/jpg'],
            resultImgId: '',
            resultImg64: '',
            resultImgUrl: '',
            isShowShared: false,
            isShowShared2: false,
            html2canvasImg: '',
            requestCount: 0,
            baseImgUrl: process.env.VUE_APP_FILE_URL
        }
    },
    methods: {
        // 修改性别
        changeSex(value) {
            if (this.userSex == value) return;
            this.userSex = value;
        },
        // 上传图片
        uploadImgFile(event) {
            if (!event.target.files[0]) return;
            const file = event.target.files[0];
            // 验证图片大小
            if (!this.imageTypeList.includes(file.type)) {
                this.$message.error('请上传.png、.jpg、.jpeg格式的图片!');
                return;
            }

            this.loading = true;
            this.blobToDataURL(file, (base64Url) => {
                // let img = document.createElement('img');
                // img.src = base64Url;
                // img.width = '376';
                // document.body.append(img);
                if (!base64Url) return;
                if (base64Url == '图片尺寸过小' || base64Url == '图片尺寸过大') {
                    this.loading = false;
                    this.$message.error(base64Url + '!');
                    // 清空文件内容
                    this.$refs.fileRef.value = '';
                    return;
                }
                this.startMergeFace(base64Url);
                // 清空文件内容
                this.$refs.fileRef.value = '';
            })
        },
        // 开始脸部融合
        startMergeFace(file) {
            const that = this;
            MergeYearFace({
                userId: this.userID,
                userType: this.userSex, // 用户男女
                img64: file, // 用户选择图片
                userChannel: this.userChannel
            })
            .then(data => {
                if (data.code == 200) {
                    if (data.data.status == 2) {
                        that.$message.error(data.data.reason);
                        that.loading = false;
                        return;
                    }
                    
                    that.resultImgUrl = data.data.userImg;
                    that.loading = false;
                    this.resultImgId = data.data.id;
                } else {
                    that.loading = false;
                    that.$message.error(data.msg);
                }
            })
            .catch(error => {
                this.loading = false;
                this.$message.error(error);
            })
        },
        // 图片转成base64
        blobToDataURL(blob, callback) {
            const that = this;
            let Orientation = 0;
            exif.getData(blob, function() {
                exif.getAllTags(this);
                Orientation = exif.getTag(this, 'Orientation');
            });

            let reader = new FileReader();
            reader.onload = (event) => {
                var base64 = event.target.result;

                let image = new Image();
                image.src = base64;

                image.onload = function (res) {
                    if (this.width < 200 && this.height < 200) {
                        callback('图片尺寸过小');
                        return;
                    }
                    // 最大尺寸限制
                    let maxWidth = 300, maxHeight = 300;
                    // 目标尺寸
                    let imageWidth = this.width;
                    let imageHeight = this.height;
                    if (this.width > maxWidth || this.height > maxHeight) {
                        if (this.width / this.height > 1) {
                            // 宽图片
                            imageWidth = maxWidth;
                            imageHeight = Math.round(maxWidth * (this.height / this.width));
                        } else {
                            // 高图片
                            imageHeight = maxHeight;
                            imageWidth = Math.round(maxHeight * (this.width / this.height));
                        }
                    }
                    let canvas = document.createElement('canvas'), // 新建canvas
                    context = canvas.getContext('2d');
                    if (that.isIOS) {
                        if (that.isIOSVersion[0] > 13 && that.isIOSVersion[1] >= 0) {
                            Orientation = 0;
                        } else if (that.isIOSVersion[0] == 13) {
                            Orientation = 0;
                        }
                    }
                    // 如果翻转
                    if (!Orientation || Orientation == 0 || Orientation == 1) {
                        // 不做任何处理直接画图
                        canvas.width = imageWidth;
                        canvas.height = imageHeight;
                    } else if (Orientation == 6) {
                        // 图片顺时针旋转90°
                        canvas.height = imageWidth;
                        canvas.width = imageHeight;
                        context.rotate(Math.PI / 2);
                        context.translate(0, -imageHeight);
                    } else if (Orientation == 3) {
                        // 图片旋转180°
                        canvas.height = imageHeight;
                        canvas.width = imageWidth;
                        context.rotate(Math.PI);
                        context.translate(-imageWidth, -imageHeight);
                    } else if (Orientation == 8) {
                        // 图片逆时针旋转90°
                        canvas.height = imageWidth;
                        canvas.width = imageHeight;
                        context.rotate(-Math.PI / 2);
                        context.translate(-imageHeight, 0);
                    }
                    context.drawImage(image, 0, 0, imageWidth, imageHeight);
                    callback(canvas.toDataURL('image/jpg')) // 回调
                }
            };
            reader.readAsDataURL(blob);
        },
        // 生成图片
        renderSharedImg() {
            const that = this;
            that.loading = true;
            if (that.resultImg64) {
                that.htmlToImg();
                return;
            }
            GetMergeYearFaceResult({
                id: that.resultImgId
            })
            .then(res => {
                if (res.code != 200) {
                    this.getBase64Image(that.resultImgUrl)
                    .then(base64 => {
                        that.resultImg64 = base64;
                        setTimeout(() => {
                           that.htmlToImg();
                        }, 1000);
                    })
                    return;
                }
                that.resultImg64 = res.data.img64;
                setTimeout(() => {
                    that.htmlToImg();
                }, 300);
            })
        },
        htmlToImg() {
            const that = this;
            html2canvas(that.$refs.sharedRef, {
                allowTaint: true, // 是否允许跨域图像污染画布
                useCORS: true, // 是否尝试使用CORS从服务器加载图像
                width: that.$refs.sharedRef.offsetWidth - 1,
                height: that.$refs.sharedRef.offsetHeight,
                scrollX: that.$refs.sharedRef.offsetLeft,
                scrollY: that.isIOS ? (-that.$refs.sharedRef.offsetTop) : 0,
                logging: false,
                scale: 1,
                dpi: 300,
                backgroundColor: null
            }).then(function(canvas) {
                that.html2canvasImg = canvas.toDataURL('image/jpg');
                that.loading = false;
                that.isShowShared = true;
            });
        },
        // 图片url转base64
        getBase64Image(imgUrl) {
            return new Promise(resolve => {
                var img = new Image();
                img.src = imgUrl;
                img.setAttribute('crossOrigin', 'anonymous');
                img.onload = (() => {
                    var canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    var ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0);
                    var dataURL = canvas.toDataURL('image/png');
                    // resolve(dataURL.replace(/^data:image\/(png|jpg);base64,/, ''));
                    resolve(dataURL);
                });
            });
        },
        // 跳转小程序登录页面
        openLoginPage() {
            if (this.userChannel == '1') {
                this.openMiniProgramPage('/pages/arthorize/index?isYear=1', 'redirectTo');
            } else if (this.userChannel == '2') {
                this.openMiniProgramPage('/pages/login/index?isYear=1', 'navigateTo');
            }
        },
        // 跳转小程序活动详情页面
        openYearPage() {
            if (this.userChannel == '1') {
                this.openMiniProgramPage('/pages/moredetail/index?isYear=1', 'redirectTo');
            } else if (this.userChannel == '2') {
                this.openMiniProgramPage('/pages/ecology/index?isYear=1', 'reLaunch');
            }
        },
        // 跳转微信小程序的某个页面
        openMiniProgramPage(url, type) {
            this.checkMiniProgramEnv()
            .then(data => {
                if (type) {
                    wx.miniProgram[type]({ url });
                } else {
                    wx.miniProgram.navigateTo({ url });
                }
            })
            .catch(error => {
                this.$message.error('请在小程序环境中打开!');
            })
        },
        // 检测是否是在小程序的环境中
        checkMiniProgramEnv() {
            return new Promise((resolve, reject) => {
                wx.miniProgram.getEnv(res => {
                    if (res.miniprogram) {
                        resolve(true);
                    } else { 
                        reject(false);
                    }
                });
            })
        },
        // 向微信小程序发送消息
        postMiniProgramMsg() {
            // wx.miniProgram.postMessage({
            //     data: {
            //         title: '分享的标题',
            //         desc:'分享的描述',
            //         path: '/pages/share/share.js'
            //     }
            // })
            this.isShowShared2 = true;
        },
        // 创建script标签，引入微信sdk
        importWxSdk() {
            const scriptTag = document.createElement('script');
            scriptTag.src = process.env.VUE_APP_WXSDK_BASEURL;
            scriptTag.type = 'text/javascript';
            document.getElementsByTagName('head')[0].append(scriptTag);
        },
        // 检测是否已经引入微信sdk文件
        checkIsImportWxSdk() {
            if (window.wx || window.jWeixin) {
                return true;
            } else {
                return false;
            }
        },
        // 屏幕适配自动修改
        fitScreenAuto() {
            const screenWidth = window.innerWidth || window.screen.width;
            if (screenWidth != 375) {
                const scaleNum = screenWidth / 375;
                this.$refs.appPageRef.style.transform = `scale(${scaleNum})`;
                this.$refs.appPageRef.style.transformOrigin = 'top left';
            }
            this.loading = false;
        },
        resetOption() {
            this.requestCount = 0;
            this.resultImgUrl = '';
            this.resultImg64 = '';
            this.resultImgId = '';
        }
    },
    created() {
        this.loading = true;
        document.getElementById('app').style.overflow = 'hidden';
        if (this.$route.query.userId && this.$route.query.userId != 'undefined') {
            this.userID = this.$route.query.userId;
        }
        if (this.$route.query.type) {
            this.userChannel = this.$route.query.type;
        }
        this.importWxSdk();
        // 判断机型
        var u = navigator.userAgent;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
        if (isiOS) {
            this.isIOS = true;
        } else if (isAndroid) {
            this.isIOS = false;
        }
        // 判断iphone的系统版本
        var ua = u.toLowerCase();
        if (ua.indexOf('like mac os x') > 0) {
            var reg = /os [\d._]*/gi ;
            var verinfo = ua.match(reg) ;
            var version = (verinfo + '').replace(/[^0-9|_.]/ig, '').replace(/_/ig, '.');
            this.isIOSVersion = version.split('.');
        }
    },
    mounted() {
        this.fitScreenAuto();
    },
    destroyed() {
        document.getElementById('app').style.overflow = 'initial';
    }
}
</script>

<style lang="scss" scoped>
h5, p {
    margin: 0;
}
.mian {
    width: 100%;
    height: 100%;
    color: white;
    background: #CA1824;
    overflow-x: hidden;
}
.app-pagemian {
    width: 375px;
    min-height: 761px;
    padding-top: 606.5px;
    padding-bottom: 94.5px;
    background: #CA1824 url('../../../assets/event_images/event_face/bg-event-face-shared1.png') no-repeat top left;
    background-size: contain;

    .my_img_1 {
        top: 210px;
        left: 34px;
    }

    .my_img_2 {
        top: 210px;
        right: 34px;
    }

    .my_img_3 {
        top: 203.5px;

        &.left {
            left: 27px;
        }

        &.right {
            right: 27px;
        }
    }

    .my_img_4 {
        top: 531.5px;
        left: 0;
        right: 0;
        margin: 0 auto;
    }

    .my_file_input {
        width: 298.5px;
        height: 51px;
        opacity: 0;
        top: 531.5px;
        left: 0;
        right: 0;
        margin: 0 auto;
        display: inline-block;
        outline: none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }

    .my_img_5{
        top: 594.5px;
        left: 0;
        right: 0;
        margin: 0 auto;
    }

    .my_img_6 {
        top: 251.5px;
        left: 0;
        right: 0;
        margin: 0 auto;
    }

    .my_img_7 {
        top: 189px;
        left: 0;
        right: 0;
        margin: 0 auto;
    }

    .event_rule {
        width: 345px;
        border-radius: 10px;
        padding: 10px 15px;
        border: 2px solid #feb9b7;
        margin: 0 auto;

        p {
            font-size: 12px;
            text-align: left;
            color: #feb9b7;
            line-height: 25px;
            letter-spacing: -1px;
        }
    }
}

.buy_car_box {
    position: fixed;
    bottom: 20px;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 95%;
    height: 65px;
    padding: 10px;
    opacity: 0.9;
    background: #ffcccc;
    border-radius: 10px;
    z-index: 11;

    .buy_car_title {
        padding-left: 10px;

        h5 {
            color: #333333;
            font-size: 16px;
            line-height: 23px;
            margin-bottom: 2px;
        }

        p {
            color: #666666;
            font-size: 12px;
            line-height: 23px;
        }
    }

    .buy_car_btn {
        height: 36px;
        font-size: 13px;
        background: #c03e3e;
        border-radius: 18px;
        line-height: 36px;
        padding: 0 7px;
    }
}

.custom_btn {
    height: 44px;
    line-height: 44px;
    background: url('../../../assets/event_images/event_face/bg-event-face-btn1.png') no-repeat top left;
    background-size: 100% 100%;
}

.my_btn_box {
    top: 564px;
    width: 80%;
    min-width: 298.5px;
    left: 0;
    right: 0;
    margin: 0 auto;

    .my_btn_1 {
        margin-bottom: 14px;
        outline: none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);

        img {
            vertical-align: sub;
        }
    }

    .my_btn_2 {
        margin-bottom: 14px;
        outline: none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }

    .my_btn_3,
    .my_btn_4 {
        width: 20%;
        min-width: 147.5px;
        height: 44px;
        line-height: 44px;
        background: url('../../../assets/event_images/event_face/bg-event-face-btn2.png') no-repeat top left;
        background-size: 100% 100%;
        outline: none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }
}

.shared_box {
    width: 752px;
    height: 1624px;
    background: url('../../../assets/event_images/event_face/bg-event-face-shared.png') no-repeat top left;
    background-size: contain;
    text-align: center;
    transform: translateX(-100%);
    top: 0;
    left: 0;
    z-index: -1;

    .my_img_8 {
        margin-top: 545px;
    }

    .my_img_9 {
        left: 0;
        bottom: 0;
    }
}

.modal {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.75);
    text-align: center;
    top: 0;
    left: 0;
    overflow: hidden;
    z-index: 11;
}

.z_index_9 {
    z-index: 9;
    outline: none;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

.el-loading-spinner {
    width: 100px;
    height: 100px;
    border-radius: 10px;
    background-color: rgba(0, 0, 0, 0.75);

    padding: 11px;
    margin: 0 auto;
    left: 0;
    right: 0;

    .el-loading-text {
        color: white;
        font-size: 12px;
        margin: 0;
        transform: scale(0.9);
        margin-top: 4px;
    }
}
</style>
